package com.example.common.codec;

import cn.hutool.json.JSONUtil;
import io.netty.buffer.ByteBuf;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
import lombok.extern.slf4j.Slf4j;

/**
 * @Author: 582895699@qq.com
 * @Desctription: 编码器
 * @Date: Created in 2021/11/28 22:13
 */
@Slf4j
public class NettyMessageEncode extends MessageToByteEncoder<NettyMessage> {

    @Override
    protected void encode(ChannelHandlerContext ctx, NettyMessage msg, ByteBuf out) throws Exception {
        Channel channel = ctx.channel();
        String jsonStr = JSONUtil.toJsonStr(msg);
        byte[] bytes = jsonStr.getBytes();
        out.writeInt(bytes.length);
        out.writeBytes(bytes);
        log.info("向[{}]编码了一条数据;jsonStr:{}", channel.id(), jsonStr);
    }
}
